const router = require('koa-router')()
const GroupHelp =require('../database/groups/GroupHelp')
const fs=require('fs')
const qr = require('qr-image')
const config=require('./config')
const VerifyUtils=require('../utils/VerifyUtils')
const baseUrl=config.baseUrl




router.get('/api/groupList',async(ctx,next)=>{

    let uid=ctx.request.query.uid
    VerifyUtils.tips(ctx,{uid})

    let data= await GroupHelp.getGroupList(uid)

    ctx.body={
        code:0,
        data:data
    }
})



router.get('/api/groupInfo',async(ctx,next)=>{

    let gid=ctx.request.query.gid
    VerifyUtils.tips(ctx,{gid})

    let data= await GroupHelp.getGroupInfo(gid)

    ctx.body={
        code:0,
        data:data
    }
})




router.get('/api/getGroupInfoByGname',async(ctx,next)=>{

    let gname=ctx.request.query.gname
    VerifyUtils.tips(ctx,{gname})

    let data= await GroupHelp.getGroupInfoByGname(gname)

    ctx.body={
        code:0,
        data:data
    }
})




router.get('/api/groupUserList',async(ctx,next)=>{

    let gid=ctx.request.query.gid
    VerifyUtils.tips(ctx,{gid})

    let data= await GroupHelp.getGroupUserList(gid)

    ctx.body={
        code:0,
        data:data
    }
})



router.get('/api/groupUserIds',async(ctx,next)=>{

    let gid=ctx.request.query.gid
    VerifyUtils.tips(ctx,{gid})

    let data= await GroupHelp.getGroupUserIds(gid)

    ctx.body={
        code:0,
        data:data
    }
})




router.post('/api/changeGroupName',async(ctx,next)=>{

    let gid=ctx.request.body.gid
    let gname=ctx.request.body.gname
    VerifyUtils.tips(ctx,{gid},{gname})

    await GroupHelp.changeGroupName(gid,gname)

    ctx.body={
        code:0,
        data:''
    }
})






router.post('/api/isGroupExist',async(ctx,next)=>{

    let gid=ctx.request.body.gid
    let uid=ctx.request.body.uid
    VerifyUtils.tips(ctx,{gid},{uid})

    let data=await GroupHelp.isGroupExist(gid,uid)

    ctx.body={
        code:0,
        data:data
    }
})







//生产二维码
router.post('/api/makeQrImg',async(ctx,next)=>{

    let text=ctx.request.body.text
    var qr_png = qr.image(text,{type: 'png',size :10})
    var imgName = +(new Date())+''+Math.ceil(Math.random()*89+10);
    imgName = `${imgName}.png`;


    var qr_pipe = qr_png.pipe(fs.createWriteStream('server/public/uploads/'+imgName));
    qr_pipe.on('error', function(err){
        console.log(err);
    })
    qr_pipe.on('finish', function(){
        console.log('finish')
    })


    let saveUrl=baseUrl+'/uploads/'+imgName
    ctx.body={
        code:0,
        data:saveUrl
    }

})





module.exports = router
